package com.jzo2o.market.handler;

import com.jzo2o.market.service.IActivityService;
import com.jzo2o.market.service.ICouponService;
import com.jzo2o.redis.sync.SyncManager;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.util.concurrent.ThreadPoolExecutor;

import static com.jzo2o.market.constants.RedisConstants.RedisKey.COUPON_SEIZE_SYNC_QUEUE_NAME;
import static com.jzo2o.redis.constants.RedisSyncQueueConstants.MODE_SINGLE;
import static com.jzo2o.redis.constants.RedisSyncQueueConstants.STORAGE_TYPE_HASH;

/**
 * XxlJob任务处理器
 * @author JIAN
 */
@Slf4j
@Component
@SuppressWarnings("unused")
public class XxlJobHandler {
    @Resource
    private IActivityService activityService;
    @Resource
    private ICouponService couponService;
    @Resource(name = "syncThreadPool")
    private ThreadPoolExecutor syncThreadPool;
    @Resource
    private SyncManager syncManager;

    /**
     * 自动修改活动状态(1分钟1次)
     * 1.活动进行中状态修改
     * 2.活动已失效状态修改
     */
    @XxlJob("updateActivityStatus")
    @Transactional
    public void updateActivityStatus() {
        log.info("自动修改活动状态任务开始");
        activityService.updateActivityStatus();
        log.info("自动修改活动状态任务完成");
    }

    /**
     * 自动过期已领取优惠券(1小时1次)
     */
    @XxlJob("processExpireCoupon")
    public void processExpireCoupon() {
        log.info("自动过期已领取优惠券任务开始");
        couponService.invalidExpiredCoupon();
        log.info("自动过期已领取优惠券任务完成");
    }

    /**
     * 自动预热(缓存)1个月内的活动
     */
    @XxlJob("activityPreheat")
    public void activityPreheat() {
        log.info("自动预热1个月内的活动任务开始");
        activityService.cacheComingActivity();
        log.info("自动预热1个月内的活动任务完成");
    }

    /**
     * 自动从Redis同步抢卷结果到数据库
     */
    @XxlJob("seizeCouponSyncJob")
    public void seizeCouponSyncJob() {
        log.info("自动从Redis同步抢卷结果到数据库任务开始");
        syncManager.start(COUPON_SEIZE_SYNC_QUEUE_NAME, STORAGE_TYPE_HASH, MODE_SINGLE, syncThreadPool);
    }
}